// internal/middleware/audit.go
package middleware

import (
	"time"

	"github.com/gin-gonic/gin"

	"github.com/jfastfiler/internal/dao"
	"github.com/jfastfiler/internal/model"
)

func AuditMiddleware(auditDAO *dao.AuditDAO) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		start := time.Now()
		
		// 处理请求
		ctx.Next()
		
		// 记录审计日志
		userID, exists := ctx.Get("user_id")
		if !exists {
			userID = 0 // 未登录用户
		}
		
		action := ctx.Request.Method + " " + ctx.Request.URL.Path
		status := "success"
		if ctx.Writer.Status() >= 400 {
			status = "failed"
		}
		
		// 获取错误信息（如果有）
		var errorMsg string
		if len(ctx.Errors) > 0 {
			errorMsg = ctx.Errors.String()
		}
		
		auditLog := &model.AuditLog{
			UserID:    userID.(int),
			Action:    action,
			Path:      ctx.Request.URL.Path,
			Details:   errorMsg,
			IP:        ctx.ClientIP(),
			UserAgent: ctx.Request.UserAgent(),
			Status:    status,
			Timestamp: start,
			Duration:  time.Since(start).Milliseconds(),
		}
		
		go auditDAO.Create(auditLog) // 异步记录，不阻塞响应
	}
}